package com.xbongbong.paas.help;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.xbongbong.paas.constant.MessageConstant;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.domain.entity.PaasFormExplainEntity;
import com.xbongbong.paas.domain.entity.PaasFormSubDataEntity;
import com.xbongbong.paas.domain.entity.PaasProcessDataEntity;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.elasticsearch.model.PaasEsModel;
import com.xbongbong.paas.elasticsearch.model.PaasFormSubDataEsModel;
import com.xbongbong.paas.elasticsearch.util.FormSubDataUtil;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.FlowStatusEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.field.ItemPoJo;
import com.xbongbong.paas.help.subform.DistributorAccountTransferSubForm;
import com.xbongbong.paas.model.PaasFormExplainModel;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.util.ExplainUtil;
import com.xbongbong.paas.util.FormDataUtil;
import com.xbongbong.pro.domain.entity.UpdateDataEntity;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.entity.ContractPerformanceEntity;
import com.xbongbong.saas.domain.entity.DistributorAccountEntity;
import com.xbongbong.saas.domain.entity.FundTransferEntity;
import com.xbongbong.saas.domain.entity.OnlinePaymentFlowEntity;
import com.xbongbong.saas.domain.entity.OtherExpenseEntity;
import com.xbongbong.saas.domain.entity.OtherIncomeEntity;
import com.xbongbong.saas.domain.entity.SpecificationEntity;
import com.xbongbong.saas.domain.entity.WorkOrderEntity;
import com.xbongbong.saas.domain.entity.competitor.CompetitorEntity;
import com.xbongbong.saas.domain.entity.ext.AssembleEntityExt;
import com.xbongbong.saas.domain.entity.ext.BomBillEntityExt;
import com.xbongbong.saas.domain.entity.ext.ClueEntityExt;
import com.xbongbong.saas.domain.entity.ext.CommunicatePlanEntityExt;
import com.xbongbong.saas.domain.entity.ext.ContactEntityExt;
import com.xbongbong.saas.domain.entity.ext.ContractEntityExt;
import com.xbongbong.saas.domain.entity.ext.CostAdjustEntityExt;
import com.xbongbong.saas.domain.entity.ext.CustomerCommunicateEntityExt;
import com.xbongbong.saas.domain.entity.ext.CustomerEntityExt;
import com.xbongbong.saas.domain.entity.ext.InstockEntityExt;
import com.xbongbong.saas.domain.entity.ext.InventoryEntityExt;
import com.xbongbong.saas.domain.entity.ext.InvoiceEntityExt;
import com.xbongbong.saas.domain.entity.ext.MarketActivityEntityExt;
import com.xbongbong.saas.domain.entity.ext.OpportunityEntityExt;
import com.xbongbong.saas.domain.entity.ext.OutstockEntityExt;
import com.xbongbong.saas.domain.entity.ext.PayPlanEntityExt;
import com.xbongbong.saas.domain.entity.ext.PayPlanSheetEntityExt;
import com.xbongbong.saas.domain.entity.ext.PaymentEntityExt;
import com.xbongbong.saas.domain.entity.ext.PaymentSheetEntityExt;
import com.xbongbong.saas.domain.entity.ext.ProductEntityExt;
import com.xbongbong.saas.domain.entity.ext.ProductionOrderEntityExt;
import com.xbongbong.saas.domain.entity.ext.PurchaseEntityExt;
import com.xbongbong.saas.domain.entity.ext.PurchaseInvoiceEntityExt;
import com.xbongbong.saas.domain.entity.ext.QuotationEntityExt;
import com.xbongbong.saas.domain.entity.ext.RefundEntityExt;
import com.xbongbong.saas.domain.entity.ext.ReturnedPurchaseEntityExt;
import com.xbongbong.saas.domain.entity.ext.SupplierCommunicateEntityExt;
import com.xbongbong.saas.domain.entity.ext.SupplierContactEntityExt;
import com.xbongbong.saas.domain.entity.ext.SupplierEntityExt;
import com.xbongbong.saas.domain.entity.ext.TransferEntityExt;
import com.xbongbong.saas.domain.entity.ext.WarehouseEntityExt;
import com.xbongbong.saas.domain.entity.ext.WorkReportEntityExt;
import com.xbongbong.saas.enums.OnlyInsertDBEnum;
import com.xbongbong.saas.enums.RedundantTemplateTypeEnum;
import com.xbongbong.saas.enums.SheetAloneEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.DistributorAccountEnum;
import com.xbongbong.saas.enums.business.DistributorEnum;
import com.xbongbong.saas.enums.business.ProductEnum;
import com.xbongbong.saas.enums.business.RefundEnum;
import com.xbongbong.saas.enums.business.ServiceProjectEnum;
import com.xbongbong.saas.help.SaasFundHelp;
import com.xbongbong.saas.model.AssembleModel;
import com.xbongbong.saas.model.BomBillModel;
import com.xbongbong.saas.model.ClueModel;
import com.xbongbong.saas.model.CommunicatePlanModel;
import com.xbongbong.saas.model.CompetitorModel;
import com.xbongbong.saas.model.ContactModel;
import com.xbongbong.saas.model.ContractModel;
import com.xbongbong.saas.model.ContractPerformanceModel;
import com.xbongbong.saas.model.CostAdjustModel;
import com.xbongbong.saas.model.CreditCardBillModel;
import com.xbongbong.saas.model.CreditFixedLimitModel;
import com.xbongbong.saas.model.CreditLimitModel;
import com.xbongbong.saas.model.CreditTemporaryLimitModel;
import com.xbongbong.saas.model.CustomerCommunicateModel;
import com.xbongbong.saas.model.CustomerModel;
import com.xbongbong.saas.model.CustomerStatementModel;
import com.xbongbong.saas.model.CustomerStatementSnapshotModel;
import com.xbongbong.saas.model.CustomerStatementStatisticsModel;
import com.xbongbong.saas.model.DistributorAccountModel;
import com.xbongbong.saas.model.ExpenseModel;
import com.xbongbong.saas.model.FundTransferModel;
import com.xbongbong.saas.model.IndexTypeModel;
import com.xbongbong.saas.model.InstockModel;
import com.xbongbong.saas.model.InventoryModel;
import com.xbongbong.saas.model.InvoiceModel;
import com.xbongbong.saas.model.MarketActivityModel;
import com.xbongbong.saas.model.OnlinePaymentFlowModel;
import com.xbongbong.saas.model.OpportunityModel;
import com.xbongbong.saas.model.OtherExpenseModel;
import com.xbongbong.saas.model.OtherIncomeModel;
import com.xbongbong.saas.model.OutstockModel;
import com.xbongbong.saas.model.PaasFormDataModel;
import com.xbongbong.saas.model.PayPlanModel;
import com.xbongbong.saas.model.PayPlanSheetModel;
import com.xbongbong.saas.model.PaymentModel;
import com.xbongbong.saas.model.PaymentSheetModel;
import com.xbongbong.saas.model.PaymentTaskModel;
import com.xbongbong.saas.model.ProductModel;
import com.xbongbong.saas.model.ProductionOrderModel;
import com.xbongbong.saas.model.PromotionActivityModel;
import com.xbongbong.saas.model.PurchaseInvoiceModel;
import com.xbongbong.saas.model.PurchaseModel;
import com.xbongbong.saas.model.QuotationModel;
import com.xbongbong.saas.model.RefundModel;
import com.xbongbong.saas.model.ReimbursementFormModel;
import com.xbongbong.saas.model.ReturnedPurchaseModel;
import com.xbongbong.saas.model.SpecificationModel;
import com.xbongbong.saas.model.SupplierCommunicateModel;
import com.xbongbong.saas.model.SupplierContactModel;
import com.xbongbong.saas.model.SupplierModel;
import com.xbongbong.saas.model.TransferModel;
import com.xbongbong.saas.model.WarehouseModel;
import com.xbongbong.saas.model.WorkOrderModel;
import com.xbongbong.saas.model.WorkReportModel;
import com.xbongbong.saas.model.WriteOffRecordModel;
import com.xbongbong.saas.toolbox.help.OnlyInsertDBHelp;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author 吴峰
 * @date 2021/05/14 14:20
 */
@Component
public class FormDataHelp {

    private static final Logger LOG = LoggerFactory.getLogger(FormDataHelp.class);

    @Resource
    private ContactModel contactModel;
    @Resource
    private OutstockModel outstockModel;
    @Resource
    private OpportunityModel opportunityModel;
    @Resource
    private WorkReportModel workReportModel;
    @Resource
    private CommunicatePlanModel communicatePlanModel;
    @Resource
    private BomBillModel bomBillModel;
    @Resource
    private CustomerCommunicateModel customerCommunicateModel;
    @Resource
    private SupplierCommunicateModel supplierCommunicateModel;
    @Resource
    private ReturnedPurchaseModel returnedPurchaseModel;
    @Resource
    private CustomerModel customerModel;
    @Resource
    private InventoryModel inventoryModel;
    @Resource
    private TransferModel transferModel;
    @Resource
    private WarehouseModel warehouseModel;
    @Resource
    private SupplierModel supplierModel;
    @Resource
    private SupplierContactModel supplierContactModel;
    @Resource
    private PurchaseModel purchaseModel;
    @Resource
    private ProductionOrderModel productionOrderModel;
    @Resource
    private ContractModel contractModel;
    @Resource
    private InvoiceModel invoiceModel;
    @Resource
    private PayPlanModel payPlanModel;
    @Resource
    private PaymentModel paymentModel;
    @Resource
    private ContractPerformanceModel contractPerformanceModel;
    @Resource
    private AssembleModel assembleModel;
    @Resource
    private InstockModel instockModel;
    @Resource
    private RefundModel refundModel;
    @Resource
    private PaymentSheetModel paymentSheetModel;
    @Resource
    private QuotationModel quotationModel;
    @Resource
    private PayPlanSheetModel payPlanSheetModel;
    @Resource
    private PurchaseInvoiceModel purchaseInvoiceModel;
    @Resource
    private ClueModel clueModel;
    @Resource
    private MarketActivityModel marketActivityModel;
    @Resource
    private PaasFormDataModel paasFormDataModel;
    @Resource
    private WorkOrderModel workOrderModel;
    @Resource
    private SaasFundHelp saasFundHelp;
    @Resource
    private SpecificationModel specificationModel;
    @Resource
    private ReimbursementFormModel reimbursementFormModel;
    @Resource
    private ExpenseModel expenseModel;
    @Resource
    private ProductModel productModel;
    @Resource
    private PaymentTaskModel paymentTaskModel;
    @Resource
    private CreditLimitModel creditLimitModel;
    @Resource
    private CreditFixedLimitModel creditFixedLimitModel;
    @Resource
    private CreditTemporaryLimitModel creditTemporaryLimitModel;
    @Resource
    private CreditCardBillModel creditCardBillModel;
    @Resource
    private CustomerStatementModel customerStatementModel;
    @Resource
    private CustomerStatementStatisticsModel customerStatementStatisticsModel;
    @Resource
    private CustomerStatementSnapshotModel customerStatementSnapshotModel;
    @Resource
    private PromotionActivityModel promotionActivityModel;
    @Resource
    private WriteOffRecordModel writeOffRecordModel;
    @Resource
    private DistributorAccountModel distributorAccountModel;
    @Resource
    private DistributorAccountTransferSubForm distributorAccountTransferSubForm;
    @Resource
    private OnlinePaymentFlowModel onlinePaymentFlowModel;
    @Resource
    private OtherIncomeModel otherIncomeModel;
    @Resource
    private OtherExpenseModel otherExpenseModel;
    @Resource
    private FundTransferModel fundTransferModel;
    @Resource
    private CostAdjustModel costAdjustModel;
    @Resource
    private PaasEsModel paasEsModel;
    @Resource
    private IndexTypeModel indexTypeModel;
    @Resource
    private PaasFormSubDataEsModel paasFormSubDataEsModel;
    @Resource
    private PaasFormExplainModel paasFormExplainModel;
    @Resource
    private CompetitorModel competitorModel;
    @Resource
    private BusinessUserTeamHelp businessUserTeamHelp;

    public List<PaasFormDataEntityExt> getByDataIdList(Collection<Long> dataIdList, Integer businessType, Integer saasMark, Long formId, String corpid) {
        return getByDataIdList(dataIdList, businessType, saasMark, formId, corpid, null);
    }
    /**
     * 根据数据id，获取多条数据
     * @param dataIdList
     * @param businessType
     * @param saasMark
     * @param corpid
     * @return
     * @throws XbbException
     */
    public List<PaasFormDataEntityExt> getByDataIdList(Collection<Long> dataIdList, Integer businessType, Integer saasMark, Long formId, String corpid, String columns) {
        if (CollectionsUtil.isEmpty(dataIdList)) {
            return new ArrayList<>();
        }
        return getByCondition(dataIdList, null, businessType, saasMark, formId, corpid, columns);
    }

    /**
     * 根据条件去检索，包括数据和流水号等
     * @param dataIdList
     * @param condition
     * @param businessType
     * @param saasMark
     * @param formId
     * @param corpid
     * @param columns
     * @return
     */
    public List<PaasFormDataEntityExt> getByCondition(Collection<Long> dataIdList, Map<String, Object> condition, Integer businessType, Integer saasMark, Long formId, String corpid, String columns) {

        List<PaasFormDataEntityExt> formDataList = new ArrayList<>();
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put(StringConstant.CORPID, corpid);
        param.put(StringConstant.IDIN, dataIdList);
        param.put(StringConstant.FORM_ID, formId);
        if (StringUtil.isNotEmpty(columns)) {
            param.put(StringConstant.COLUMNS, columns);
        }
        if (Objects.nonNull(condition) && !condition.isEmpty()) {
            param.putAll(condition);
        }
        try {
            if (Objects.equals(SaasMarkEnum.SAAS.getCode(), saasMark)) {
                XbbRefTypeEnum xbbRefTypeEnum = XbbRefTypeEnum.getByCode(businessType);
                switch (xbbRefTypeEnum) {
                    case CUSTOMER_MANAGEMENT:
                        List<CustomerEntityExt> customerList  = customerModel.findEntitys(param);
                        BeanUtil.copyPropertiesList(customerList, formDataList, PaasFormDataEntityExt.class);
                        break;
                    case COMPETITOR:
                        List<CompetitorEntity> competitorList = competitorModel.findEntitys(param);
                        BeanUtil.copyPropertiesList(competitorList,formDataList,PaasFormDataEntityExt.class);
                        break;
                    case CONTACT:
                        List<ContactEntityExt> contactList  = contactModel.findEntitys(param);
                        BeanUtil.copyPropertiesList(contactList, formDataList, PaasFormDataEntityExt.class);
                        break;
                    case CUSTOMER_COMMUNICATE:
                        List<CustomerCommunicateEntityExt> customerCommunicateList = customerCommunicateModel.findEntitys(param);
                        BeanUtil.copyPropertiesList(customerCommunicateList, formDataList, PaasFormDataEntityExt.class);
                        break;
                    case COMMUNICATE_PLAN:
                        List<CommunicatePlanEntityExt>  communicatePlanList = communicatePlanModel.findEntitys(param);
                        BeanUtil.copyPropertiesList(communicatePlanList, formDataList, PaasFormDataEntityExt.class);
                        break;
                    case SALES_OPPORTUNITY:
                        List<OpportunityEntityExt>  opportunityList = opportunityModel.findEntitys(param);
                        BeanUtil.copyPropertiesList(opportunityList, formDataList, PaasFormDataEntityExt.class);
                        break;
                    case CONTRACT:
                        List<ContractEntityExt>  contractList = contractModel.findEntitys(param);
                        BeanUtil.copyPropertiesList(contractList, formDataList, PaasFormDataEntityExt.class);
                        break;
                    case REFUND:
                        List<RefundEntityExt> refundList = refundModel.findEntitys(param);
                        BeanUtil.copyPropertiesList(refundList, formDataList, PaasFormDataEntityExt.class);
                        break;
                    case WORK_REPORT:
                    case WORKREPORT_WEEKLY:
                    case WORKREPORT_DAILY:
                    case WORKREPORT_MONTHLY:
                        List<WorkReportEntityExt> workReportList = workReportModel.findEntitys(param);
                        BeanUtil.copyPropertiesList(workReportList, formDataList, PaasFormDataEntityExt.class);
                        break;
                    case SUPPLIER:
                        List<SupplierEntityExt>  supplierList = supplierModel.findEntitys(param);
                        BeanUtil.copyPropertiesList(supplierList, formDataList, PaasFormDataEntityExt.class);
                        break;
                    case SUPPLIER_CONTACT:
                        List<SupplierContactEntityExt> supplierContactList = supplierContactModel.findEntitys(param);
                        BeanUtil.copyPropertiesList(supplierContactList, formDataList, PaasFormDataEntityExt.class);
                        break;
                    case SUPPLIER_COMMUNICATE:
                        List<SupplierCommunicateEntityExt>  supplierCommunicateList = supplierCommunicateModel.findEntitys(param);
                        BeanUtil.copyPropertiesList(supplierCommunicateList, formDataList, PaasFormDataEntityExt.class);
                        break;
                    case PURCHASE:
                        List<PurchaseEntityExt> purchaseList = purchaseModel.findEntitys(param);
                        BeanUtil.copyPropertiesList(purchaseList, formDataList, PaasFormDataEntityExt.class);
                        break;
                    case RETURNED_PURCHASE:
                        List<ReturnedPurchaseEntityExt> returnedPurchaseList = returnedPurchaseModel.findEntitys(param);
                        BeanUtil.copyPropertiesList(returnedPurchaseList, formDataList, PaasFormDataEntityExt.class);
                        break;
                    case BOM_BILL:
                        List<BomBillEntityExt> bomList = bomBillModel.findEntitys(param);
                        BeanUtil.copyPropertiesList(bomList, formDataList, PaasFormDataEntityExt.class);
                        break;
                    case PRODUCTION_ORDER:
                        List<ProductionOrderEntityExt> productionOrderList = productionOrderModel.findEntitys(param);
                        BeanUtil.copyPropertiesList(productionOrderList, formDataList, PaasFormDataEntityExt.class);
                        break;
                    case ASSEMBLE:
                        List<AssembleEntityExt> assembleList = assembleModel.findEntitys(param);
                        BeanUtil.copyPropertiesList(assembleList, formDataList, PaasFormDataEntityExt.class);
                        break;
                    case INSTOCK:
                    case PURCHASE_INSTOCK:
                    case OTHER_INSTOCK:
                    case REFUND_INSTOCK:
                    case RETURNED_MATERIEL_INSTOCK:
                    case PRODUCTION_INSTOCK:
                        List<InstockEntityExt> instockList = instockModel.findEntitys(param);
                        BeanUtil.copyPropertiesList(instockList, formDataList, PaasFormDataEntityExt.class);
                        break;
                    case OUTSTOCK:
                    case CONTRACT_OUTSTOCK:
                    case OTHER_OUTSTOCK:
                    case RETURNED_PURCHASE_OUTSTOCK:
                    case PRODUCTION_MATERIEL_OUTSTOCK:
                    case WORK_ORDER_OUTSTOCK:
                        List<OutstockEntityExt> outstockList = outstockModel.findEntitys(param);
                        BeanUtil.copyPropertiesList(outstockList, formDataList, PaasFormDataEntityExt.class);
                        break;
                    case INVENTORY:
                        List<InventoryEntityExt> inventoryList = inventoryModel.findEntitys(param);
                        BeanUtil.copyPropertiesList(inventoryList, formDataList, PaasFormDataEntityExt.class);
                        break;
                    case TRANSFER:
                        List<TransferEntityExt> transferList = transferModel.findEntitys(param);
                        BeanUtil.copyPropertiesList(transferList, formDataList, PaasFormDataEntityExt.class);
                        break;
                    case WAREHOUSE:
                        List<WarehouseEntityExt> warehouseList = warehouseModel.findEntitys(param);
                        BeanUtil.copyPropertiesList(warehouseList, formDataList, PaasFormDataEntityExt.class);
                        break;
                    case PAYMENT:
                        List<PaymentEntityExt> paymentList = paymentModel.findEntitys(param);
                        BeanUtil.copyPropertiesList(paymentList, formDataList, PaasFormDataEntityExt.class);
                        break;
                    case PAY_PLAN:
                        List<PayPlanEntityExt> payPlanList = payPlanModel.findEntitys(param);
                        BeanUtil.copyPropertiesList(payPlanList, formDataList, PaasFormDataEntityExt.class);
                        break;
                    case INVOICE:
                        List<InvoiceEntityExt> invoiceList = invoiceModel.findEntitys(param);
                        BeanUtil.copyPropertiesList(invoiceList, formDataList, PaasFormDataEntityExt.class);
                        break;
                    case WORK_ORDER:
                        List<WorkOrderEntity> workOrderList = workOrderModel.findEntitys(param);
                        BeanUtil.copyPropertiesList(workOrderList, formDataList, PaasFormDataEntityExt.class);
                        break;
                    case PRODUCT:
                        List<ProductEntityExt> productEntityList = productModel.findEntitys(param);
                        BeanUtil.copyPropertiesList(productEntityList, formDataList, PaasFormDataEntityExt.class);
                        break;
                    case PAYMENT_SHEET:
                    case BAD_DEBT:
                    case WRITE_OFF_PREPAYMENT:
                    case RED_PAYMENT_SHEET:
                    case RED_WRITE_OFF_PREPAYMENT:
                    case RED_PREPAYMENT:
                    case PREPAYMENT:
                        List<PaymentSheetEntityExt> paymentSheetList = paymentSheetModel.findEntitys(param);
                        BeanUtil.copyPropertiesList(paymentSheetList, formDataList, PaasFormDataEntityExt.class);
                        break;
                    case PAY_SHEET:
                    case PREPAY:
                    case WRITE_OFF_PREPAY:
                    case RED_WRITE_OFF_PAY:
                    case RED_WRITE_OFF_PREPAY:
                    case RED_PREPAY:
                    case BAD_PAY:
                        List<PayPlanSheetEntityExt> payPlanSheetList = payPlanSheetModel.findEntitys(param);
                        BeanUtil.copyPropertiesList(payPlanSheetList, formDataList, PaasFormDataEntityExt.class);
                        break;
                    case PURCHASE_INVOICE:
                        List<PurchaseInvoiceEntityExt> purchaseInvoiceList = purchaseInvoiceModel.findEntitys(param);
                        BeanUtil.copyPropertiesList(purchaseInvoiceList, formDataList, PaasFormDataEntityExt.class);
                        break;
                    case OTHER_INCOME:
                    case RED_OTHER_INCOME:
                        List<OtherIncomeEntity> otherIncomeEntities = otherIncomeModel.findEntitys(param);
                        BeanUtil.copyPropertiesList(otherIncomeEntities, formDataList, PaasFormDataEntityExt.class);
                        break;
                    case OTHER_EXPENSE:
                    case RED_OTHER_EXPENSE:
                        List<OtherExpenseEntity> otherExpenseEntities = otherExpenseModel.findEntitys(param);
                        BeanUtil.copyPropertiesList(otherExpenseEntities, formDataList, PaasFormDataEntityExt.class);
                        break;
                    case FUND_TRANSFER:
                        List<FundTransferEntity> fundTransferEntities = fundTransferModel.findEntitys(param);
                        BeanUtil.copyPropertiesList(fundTransferEntities, formDataList, PaasFormDataEntityExt.class);
                        break;
                    case QUOTATION:
                        List<QuotationEntityExt> quotationList = quotationModel.findEntitys(param);
                        BeanUtil.copyPropertiesList(quotationList, formDataList, PaasFormDataEntityExt.class);
                        break;
                    case CLUE:
                        List<ClueEntityExt> clueList = clueModel.findEntitys(param);
                        BeanUtil.copyPropertiesList(clueList, formDataList, PaasFormDataEntityExt.class);
                        break;
                    case MARKET_ACTIVITY:
                        List<MarketActivityEntityExt> marketActivityList = marketActivityModel.findEntitys(param);
                        BeanUtil.copyPropertiesList(marketActivityList, formDataList, PaasFormDataEntityExt.class);
                        break;
                    case COST_ADJUST:
                        List<CostAdjustEntityExt> costAdjustEntityExtList = costAdjustModel.findEntitys(param);
                        BeanUtil.copyPropertiesList(costAdjustEntityExtList, formDataList, PaasFormDataEntityExt.class);
                        break;
                    case SERVICE_PROJECT:
                    case WORK_ORDER_V2:
                    case RECEIPT_ORDER:
                    case SLA_LOG:
                        IndexTypeEnum indexTypeEnum = indexTypeModel.getIndexType(corpid, businessType, saasMark);
                        formDataList = paasEsModel.getByIdList(dataIdList, corpid, null, indexTypeEnum, PaasFormDataEntityExt.class);
                        if (CollectionUtils.isNotEmpty(formDataList)) {
                            IndexTypeEnum subIndex = indexTypeModel.getSubIndexType(corpid, businessType, SaasMarkEnum.SAAS.getCode());
                            List<Long> dataIdIn = new ArrayList<>();
                            formDataList.forEach(item->{
                                dataIdIn.add(item.getDataId());
                            });
                            List<PaasFormSubDataEntity> subDataList = paasFormSubDataEsModel.getSubDataByParentId(corpid, SaasMarkEnum.SAAS.getCode(), businessType, null, formId, dataIdIn, 1, null, subIndex);
                            if (CollectionUtils.isNotEmpty(subDataList)) {
                                FormSubDataUtil.setSubData(formDataList, subDataList);
                            }
                        }
                        break;
                    default:
                        break;
                }
            } else {
                formDataList = paasFormDataModel.findEntitys(param);
            }
            if (Objects.isNull(formDataList)) {
                return new ArrayList<>();
            }
        } catch (Exception e) {
            LOG.error("getDataByDataIdList查询数据：", e);
        }
        formDataList.forEach(formData -> {
            formData.setBusinessType(businessType);
            formData.setSaasMark(saasMark);
        });
        return formDataList;
    }

    /**
     * 编辑进审批，流程状态修改后修改原数据状态
     * @param paasProcessDataEntity
     */
    public void updateFormDataStatus(PaasProcessDataEntity paasProcessDataEntity, Integer flowStatus) throws XbbException {
        if (Objects.isNull(flowStatus)) {
            return;
        }
        Integer saasMark = paasProcessDataEntity.getSaasMark();
        Integer businessType = paasProcessDataEntity.getBusinessType();
        Long formDataId = paasProcessDataEntity.getFormDataId();
        String corpid = paasProcessDataEntity.getCorpid();
        Integer del = paasProcessDataEntity.getDel();
        // 下方所有的会将del赋值，避免更新掉del，因为工作流可能会自己删除自己后再调用此方法会将del再置回0
        if (SaasMarkEnum.SAAS.getCode().equals(saasMark)) {
            RedundantTemplateTypeEnum redundantTemplateTypeEnum = RedundantTemplateTypeEnum.getByCode(businessType);
            switch (redundantTemplateTypeEnum) {
                case CUSTOMER:
                    CustomerEntityExt customerEntity = new CustomerEntityExt();
                    customerEntity.setId(formDataId);
                    customerEntity.setCorpid(corpid);
                    customerEntity.setFlowStatus(flowStatus);
                    customerEntity.setDel(del);
                    customerModel.update(customerEntity);
                    break;
                case SALES_OPPORTUNITY:
                    OpportunityEntityExt opportunityEntity = new OpportunityEntityExt();
                    opportunityEntity.setCorpid(corpid);
                    opportunityEntity.setId(formDataId);
                    opportunityEntity.setFlowStatus(flowStatus);
                    opportunityEntity.setDel(del);
                    opportunityModel.update(opportunityEntity);
                    break;
                case CONTRACT:
                    ContractEntityExt contractEntity = new ContractEntityExt();
                    contractEntity.setCorpid(corpid);
                    contractEntity.setId(formDataId);
                    contractEntity.setFlowStatus(flowStatus);
                    contractEntity.setDel(del);
                    contractModel.update(contractEntity);
                    List<ContractPerformanceEntity> updateDelList = new ArrayList<>();
                    if (Objects.equals(flowStatus, FlowStatusEnum.PASS.getType()) || Objects.equals(flowStatus, FlowStatusEnum.NOT_NEED_APPROVAL.getType())) {
                        contractPerformanceModel.setApprovalByContractId(formDataId, corpid, DelEnum.NORMAL.getDel(), updateDelList);
                    } else {
                        contractPerformanceModel.setApprovalByContractId(formDataId, corpid, DelEnum.APPROVE_STATUS.getDel(), updateDelList);
                    }
                    // todo 合同业绩分配操作日志
                    break;
                case REFUND:
                    RefundEntityExt refundEntity = new RefundEntityExt();
                    refundEntity.setCorpid(corpid);
                    refundEntity.setId(formDataId);
                    refundEntity.setFlowStatus(flowStatus);
                    refundEntity.setDel(del);
                    refundModel.update(refundEntity);
                    RefundEntityExt refundEntityExt = refundModel.getByKey(formDataId, corpid);
                    if (Objects.nonNull(refundEntityExt)) {
                        Long redContractId = refundEntityExt.getData().getLong(RefundEnum.RED_CONTRACT_ID.getAttr());
                        if (Objects.nonNull(redContractId)) {
                            ContractEntityExt redContractEntity = new ContractEntityExt();
                            redContractEntity.setCorpid(corpid);
                            redContractEntity.setId(redContractId);
                            redContractEntity.setFlowStatus(flowStatus);
                            contractModel.update(redContractEntity);
                        }
                    }
                    break;
                case BOMBILL:
                    BomBillEntityExt bomBillEntity = new BomBillEntityExt();
                    bomBillEntity.setCorpid(corpid);
                    bomBillEntity.setId(formDataId);
                    bomBillEntity.setFlowStatus(flowStatus);
                    bomBillEntity.setDel(del);
                    bomBillModel.update(bomBillEntity);
                    break;
                case PRODUCTIONORDER:
                    ProductionOrderEntityExt productionOrderEntity = new ProductionOrderEntityExt();
                    productionOrderEntity.setCorpid(corpid);
                    productionOrderEntity.setId(formDataId);
                    productionOrderEntity.setFlowStatus(flowStatus);
                    productionOrderEntity.setDel(del);
                    productionOrderModel.update(productionOrderEntity);
                    break;
                case INSTOCK:
                case PURCHASE_INSTOCK:
                case REFUND_INSTOCK:
                case OTHER_INSTOCK:
                case PRODUCTION_INSTOCK:
                case RETURNED_MATERIEL_INSTOCK:
                    InstockEntityExt instockEntity = new InstockEntityExt();
                    instockEntity.setCorpid(corpid);
                    instockEntity.setId(formDataId);
                    instockEntity.setFlowStatus(flowStatus);
                    instockEntity.setDel(del);
                    instockModel.update(instockEntity);
                    break;
                case OUTSTOCK:
                case CONTRACT_OUTSTOCK:
                case OTHER_OUTSTOCK:
                case RETURNED_PURCHASE_OUTSTOCK:
                case WORK_ORDER_OUTSTOCK:
                case PRODUCTION_MATERIEL_OUTSTOCK:
                    OutstockEntityExt outstockEntity = new OutstockEntityExt();
                    outstockEntity.setCorpid(corpid);
                    outstockEntity.setId(formDataId);
                    outstockEntity.setFlowStatus(flowStatus);
                    outstockEntity.setDel(del);
                    outstockModel.update(outstockEntity);
                    break;
                case TRANSFER:
                    TransferEntityExt transferEntity = new TransferEntityExt();
                    transferEntity.setCorpid(corpid);
                    transferEntity.setId(formDataId);
                    transferEntity.setFlowStatus(flowStatus);
                    transferEntity.setDel(del);
                    transferModel.update(transferEntity);
                    break;
                case INVENTORY:
                    InventoryEntityExt inventoryEntity = new InventoryEntityExt();
                    inventoryEntity.setCorpid(corpid);
                    inventoryEntity.setId(formDataId);
                    inventoryEntity.setFlowStatus(flowStatus);
                    inventoryEntity.setDel(del);
                    inventoryModel.update(inventoryEntity);
                    break;
                case ASSEMBLE:
                    AssembleEntityExt assembleEntity = new AssembleEntityExt();
                    assembleEntity.setCorpid(corpid);
                    assembleEntity.setId(formDataId);
                    assembleEntity.setFlowStatus(flowStatus);
                    assembleEntity.setDel(del);
                    assembleModel.update(assembleEntity);
                    break;
                case PURCHASE:
                    PurchaseEntityExt purchaseEntity = new PurchaseEntityExt();
                    purchaseEntity.setCorpid(corpid);
                    purchaseEntity.setId(formDataId);
                    purchaseEntity.setFlowStatus(flowStatus);
                    purchaseEntity.setDel(del);
                    purchaseModel.update(purchaseEntity);
                    break;
                case RETURNED_PURCHASE:
                    ReturnedPurchaseEntityExt returnedPurchaseEntity = new ReturnedPurchaseEntityExt();
                    returnedPurchaseEntity.setCorpid(corpid);
                    returnedPurchaseEntity.setId(formDataId);
                    returnedPurchaseEntity.setFlowStatus(flowStatus);
                    returnedPurchaseEntity.setDel(del);
                    returnedPurchaseModel.update(returnedPurchaseEntity);
                    break;
                case INVOICE:
                    InvoiceEntityExt invoiceEntity = new InvoiceEntityExt();
                    invoiceEntity.setCorpid(corpid);
                    invoiceEntity.setId(formDataId);
                    invoiceEntity.setFlowStatus(flowStatus);
                    invoiceEntity.setDel(del);
                    invoiceModel.update(invoiceEntity);
                    break;
                case PURCHASE_INVOICE:
                    PurchaseInvoiceEntityExt purchaseInvoiceEntityExt = new PurchaseInvoiceEntityExt();
                    purchaseInvoiceEntityExt.setCorpid(corpid);
                    purchaseInvoiceEntityExt.setId(formDataId);
                    purchaseInvoiceEntityExt.setFlowStatus(flowStatus);
                    purchaseInvoiceEntityExt.setDel(del);
                    purchaseInvoiceModel.update(purchaseInvoiceEntityExt);
                    break;
                case WORKORDER:
                    WorkOrderEntity workOrderEntity = new WorkOrderEntity(null);
                    workOrderEntity.setCorpid(corpid);
                    workOrderEntity.setId(formDataId);
                    workOrderEntity.setFlowStatus(flowStatus);
                    workOrderEntity.setDel(del);
                    workOrderModel.update(workOrderEntity);
                    break;
                case PAYMENT_SHEET:
                    //需要读出回款单数据，判断其alone值，如果是父的，还需要联动更新子回款单审批状态
                    PaymentSheetEntityExt paymentSheetEntityExt = paymentSheetModel.getByKey(formDataId, corpid);
                    if (paymentSheetEntityExt == null) {
                        break;
                    } else if (Objects.equals(paymentSheetEntityExt.getAlone(), SheetAloneEnum.PARENT.getCode())) {
                        List<UpdateDataEntity> updateList = getUpdateDataList4Sheet(flowStatus, formDataId, corpid, IndexTypeEnum.IDX_SAAS_PAYMENT_SHEET, paymentSheetEntityExt.getUuid());
                        paymentSheetModel.updateFlowStatusBatch(updateList, corpid);
                    } else {
                        PaymentSheetEntityExt updatePaymentSheet = new PaymentSheetEntityExt();
                        updatePaymentSheet.setCorpid(corpid);
                        updatePaymentSheet.setId(formDataId);
                        updatePaymentSheet.setFlowStatus(flowStatus);
                        updatePaymentSheet.setDel(del);
                        paymentSheetModel.update(updatePaymentSheet);
                    }
                    break;
                case PAY_SHEET:
                    //需要读出付款单数据，判断其alone值，如果是父的，还需要联动更新子付款单审批状态
                    PayPlanSheetEntityExt payPlanSheetEntityExt = payPlanSheetModel.getByKey(formDataId, corpid);
                    if (payPlanSheetEntityExt == null) {
                        break;
                    } else if (Objects.equals(payPlanSheetEntityExt.getAlone(), SheetAloneEnum.PARENT.getCode())) {
                        List<UpdateDataEntity> updateList = getUpdateDataList4Sheet(flowStatus, formDataId, corpid, IndexTypeEnum.IDX_SAAS_PAYPLAN_SHEET, payPlanSheetEntityExt.getUuid());
                        payPlanSheetModel.updateFlowStatusBatch(updateList, corpid);
                    } else {
                        PayPlanSheetEntityExt updatePayPlanSheet = new PayPlanSheetEntityExt();
                        updatePayPlanSheet.setCorpid(corpid);
                        updatePayPlanSheet.setId(formDataId);
                        updatePayPlanSheet.setFlowStatus(flowStatus);
                        updatePayPlanSheet.setDel(del);
                        payPlanSheetModel.update(updatePayPlanSheet);
                    }
                    break;
                case QUOTATION:
                    QuotationEntityExt quotationEntityExt = new QuotationEntityExt();
                    quotationEntityExt.setCorpid(corpid);
                    quotationEntityExt.setId(formDataId);
                    quotationEntityExt.setFlowStatus(flowStatus);
                    quotationEntityExt.setDel(del);
                    quotationModel.update(quotationEntityExt);
                    break;
                case SUPPLIER:
                    SupplierEntityExt supplierEntityExt = new SupplierEntityExt();
                    supplierEntityExt.setCorpid(corpid);
                    supplierEntityExt.setId(formDataId);
                    supplierEntityExt.setFlowStatus(flowStatus);
                    supplierEntityExt.setDel(del);
                    supplierModel.update(supplierEntityExt);
                    break;
                case SUPPLIER_CONTACT:
                    SupplierContactEntityExt supplierContactEntityExt = new SupplierContactEntityExt();
                    supplierContactEntityExt.setCorpid(corpid);
                    supplierContactEntityExt.setId(formDataId);
                    supplierContactEntityExt.setFlowStatus(flowStatus);
                    supplierContactEntityExt.setDel(del);
                    supplierContactModel.update(supplierContactEntityExt);
                    break;
                case CONTACT:
                    ContactEntityExt contactEntityExt = new ContactEntityExt();
                    contactEntityExt.setCorpid(corpid);
                    contactEntityExt.setId(formDataId);
                    contactEntityExt.setFlowStatus(flowStatus);
                    contactEntityExt.setDel(del);
                    contactModel.update(contactEntityExt);
                    break;
                case CLUE:
                    ClueEntityExt clueEntityExt = new ClueEntityExt();
                    clueEntityExt.setCorpid(corpid);
                    clueEntityExt.setId(formDataId);
                    clueEntityExt.setFlowStatus(flowStatus);
                    clueEntityExt.setDel(del);
                    clueModel.update(clueEntityExt);
                    break;
                case MARKET_ACTIVITY:
                    MarketActivityEntityExt marketActivityEntityExt = new MarketActivityEntityExt();
                    marketActivityEntityExt.setCorpid(corpid);
                    marketActivityEntityExt.setId(formDataId);
                    marketActivityEntityExt.setFlowStatus(flowStatus);
                    marketActivityEntityExt.setDel(del);
                    marketActivityModel.update(marketActivityEntityExt);
                    break;
                case OTHER_INCOME:
                    OtherIncomeEntity otherIncomeEntity = new OtherIncomeEntity();
                    otherIncomeEntity.setCorpid(corpid);
                    otherIncomeEntity.setId(formDataId);
                    otherIncomeEntity.setFlowStatus(flowStatus);
                    otherIncomeEntity.setDel(del);
                    otherIncomeModel.update(otherIncomeEntity);
                    break;
                case OTHER_EXPENSE:
                    OtherExpenseEntity otherExpenseEntity = new OtherExpenseEntity();
                    otherExpenseEntity.setCorpid(corpid);
                    otherExpenseEntity.setId(formDataId);
                    otherExpenseEntity.setFlowStatus(flowStatus);
                    otherExpenseEntity.setDel(del);
                    otherExpenseModel.update(otherExpenseEntity);
                    break;
                case FUND_TRANSFER:
                    FundTransferEntity fundTransferEntity = new FundTransferEntity();
                    fundTransferEntity.setCorpid(corpid);
                    fundTransferEntity.setId(formDataId);
                    fundTransferEntity.setFlowStatus(flowStatus);
                    fundTransferEntity.setDel(del);
                    fundTransferModel.update(fundTransferEntity);
                    break;
                case COST_ADJUST:
                    CostAdjustEntityExt costAdjustEntityExt = new CostAdjustEntityExt();
                    costAdjustEntityExt.setCorpid(corpid);
                    costAdjustEntityExt.setId(formDataId);
                    costAdjustEntityExt.setFlowStatus(flowStatus);
                    costAdjustEntityExt.setDel(del);
                    costAdjustModel.updateFlowStatus(costAdjustEntityExt);
                    break;
                case COMPETITOR:
                    CompetitorEntity competitorEntity = new CompetitorEntity();
                    competitorEntity.setCorpid(corpid);
                    competitorEntity.setId(formDataId);
                    competitorEntity.setFlowStatus(flowStatus);
                    competitorEntity.setDel(del);
                    competitorModel.update(competitorEntity);
                default:
                    break;
            }
        } else {
            PaasFormDataEntity paasFormDataEntity = new PaasFormDataEntity();
            paasFormDataEntity.setCorpid(corpid);
            paasFormDataEntity.setId(formDataId);
            paasFormDataEntity.setFlowStatus(flowStatus);
            paasFormDataEntity.setDel(del);
            paasFormDataModel.update(paasFormDataEntity);
        }
    }

    /**
     * 把父单、子单都塞入要更新的updateList内：更新父单审批状态时，需要同步更新子单的审批状态
     * @param flowStatus 审批状态
     * @param formDataId 数据id
     * @param corpid 公司id
     * @param indexTypeEnum 回/付款单es索引
     * @param uuid 回/付款单uuid
     * @return java.util.List<com.xbongbong.pro.domain.entity.UpdateDataEntity>
     * @throws XbbException
     * @author zcp
     * @since v1.0
     * @version v1.0
     */
    public List<UpdateDataEntity> getUpdateDataList4Sheet(Integer flowStatus, Long formDataId, String corpid, IndexTypeEnum indexTypeEnum, String uuid) throws XbbException {
        List<UpdateDataEntity> updateList = new ArrayList<>();
        long now = DateUtil.getNow();
        //把数据本身置入要更新的list
        updateList.add(new UpdateDataEntity(formDataId, corpid, flowStatus, new ArrayList<>(), now));
        List<PaasFormDataEntityExt> childList = saasFundHelp.getEsDataListByUuidAndAlone(indexTypeEnum, corpid,SheetAloneEnum.CHILD, uuid, null);
        for (PaasFormDataEntityExt entityExt : childList) {
            UpdateDataEntity updateDataEntity = new UpdateDataEntity(entityExt.getId(), corpid, flowStatus, new ArrayList<>(), now);
            updateList.add(updateDataEntity);
        }
        return updateList;
    }

    /**
     * 子产品多规格渲染
     * @param paasFormDataESList
     * @param corpid
     */
    public void setChildSpecification(List<PaasFormDataEntityExt> paasFormDataESList, String corpid) {
        List<Long> parentIdList = new ArrayList<>();
        for (PaasFormDataEntityExt entityExt : paasFormDataESList){
            if (Objects.nonNull(entityExt.getData())) {
                Long parentId = Objects.isNull(entityExt.getData().getLong(ProductEnum.PARENT_ID.getAttr())) ? 0L : entityExt.getData().getLong(ProductEnum.PARENT_ID.getAttr());
                parentIdList.add(parentId);
            }
        }
        Map<Long, List<SpecificationEntity>> specificationMap = specificationModel.getSpecificationMap(corpid, parentIdList);
        for (PaasFormDataEntityExt entityExt : paasFormDataESList){
            JSONObject data = entityExt.getData();
            Long parentId = data.getLong(ProductEnum.PARENT_ID.getAttr()) == null ? 0L : entityExt.getData().getLong(ProductEnum.PARENT_ID.getAttr());
            try {
                String specStr = decodeSpec(data.getString(ProductEnum.SPECIFICATION.getAttr()),data.getString(ProductEnum.SPECIFICATION_LINK_TEXT.getAttr()),specificationMap.getOrDefault(parentId,new ArrayList<>()));
                data.put(ProductEnum.SPECIFICATION.getAttr(),specStr);
                data.put(ProductEnum.SPECIFICATION_LINK_TEXT.getAttr(),specStr);
            }catch (Exception e){
                LOG.error("decodeSpec json:" + JSONObject.toJSONString(data));
                LOG.error("decodeSpec:",e);
            }
        }
    }

    /**
     * 服务项目单位渲染
     * @param paasFormDataESList
     * @param corpid
     */
    public void setServiceUnit(List<PaasFormDataEntityExt> paasFormDataESList, String corpid) {
        try {
            PaasFormExplainEntity formExplainEntity = paasFormExplainModel.getByBusinessType(XbbRefTypeEnum.SERVICE_PROJECT.getCode(), corpid);
            Map<String, FieldAttrEntity> explainMap = ExplainUtil.getExplainMap(formExplainEntity.getExplains(), null);
            String unitAttr = ServiceProjectEnum.UNIT.getAttr();
            if (MapUtils.isEmpty(explainMap) || !explainMap.containsKey(unitAttr)) {
                return;
            }
            FieldAttrEntity fieldAttrEntity = explainMap.get(unitAttr);
            List<ItemPoJo> items = fieldAttrEntity.getItems();
            if (CollectionsUtil.isEmpty(items)) {
                return;
            }
            Map<String, ItemPoJo> serviceUnitMap = new HashMap<>();
            for (ItemPoJo item : items) {
                serviceUnitMap.put(item.getValue().toString(), item);
            }
            for (PaasFormDataEntityExt entityExt : paasFormDataESList) {
                JSONObject data = entityExt.getData();
                String unit = data.getString(ServiceProjectEnum.UNIT.getAttr());
                if (StringUtil.isNotEmpty(unit)) {
                    Object unitObject = Objects.isNull(serviceUnitMap.get(unit)) ? null : serviceUnitMap.get(unit).getValue();
                    data.put(ServiceProjectEnum.UNIT.getAttr(), unitObject);
                }
            }
        } catch (Exception e) {
            LOG.error("com.xbongbong.paas.help.FormDataHelp.setServiceUnit error:",  e);
        }
    }

    /**
     * 规格解析
     * @param isSpec 1为多规格 0为单规格
     * @param specStr 数据格式 ： "{\"颜色\":\"原谅绿\",\"尺寸\":\"大\"}"
     * @param specificationLiist 数据库规格 null时表示不需要排序
     * @return 原谅绿/大
     */
    public String decodeSpec(String isSpec, String specStr, List<SpecificationEntity> specificationLiist) {
        StringBuilder stringBuilder = new StringBuilder();
        if (Objects.equals(isSpec,"1")){
            JSONObject specifition = JSONObject.parseObject(specStr);
            specifition = Objects.isNull(specifition) ? new JSONObject() : specifition;
            Map<String, String> specMap = JSONObject.parseObject(specifition.toJSONString(), new TypeReference<Map<String, String>>(){});
            if (Objects.nonNull(specificationLiist)) {
                for (SpecificationEntity specificationEntity : specificationLiist) {
                    if (specMap.containsKey(specificationEntity.getName())) {
                        if (StringUtil.isNotEmpty(specMap.get(specificationEntity.getName()))) {
                            StringUtil.stringBuilderAppendSuffix(stringBuilder,"/",specMap.get(specificationEntity.getName()));
                        }
                    }
                }
            }else {
                for (Map.Entry entry : specifition.entrySet()){
                    StringUtil.stringBuilderAppendSuffix(stringBuilder,"/",entry.getValue());
                }
            }
        }else if (StringUtil.isNotEmpty(specStr)) {
            stringBuilder.append(specStr);
        }
        return stringBuilder.toString();
    }
    /**
     * 返回数据实体
     * @param corpid
     * @param saasMark
     * @param businessType
     * @param dataId
     * @return
     * @throws XbbException
     */
    public PaasFormDataEntity getFormDataEntity(String corpid, Integer saasMark, Integer businessType, Long dataId) throws XbbException {
        return getFormDataEntityExt(corpid, saasMark, businessType, dataId);
    }
    /**
     * 获取实体，返回null值
     * @param corpid
     * @param saasMark
     * @param businessType
     * @param dataId
     * @return
     * @throws XbbException
     */
    public PaasFormDataEntityExt getFormData(String corpid, Integer saasMark, Integer businessType, Long dataId) throws XbbException {
        PaasFormDataEntityExt paasFormDataEntityExt;
        if (Objects.equals(saasMark, SaasMarkEnum.PAAS.getCode())) {
            paasFormDataEntityExt = paasFormDataModel.getByKey(dataId, corpid);
        } else {
            paasFormDataEntityExt = getFormData(dataId, corpid, businessType);
        }
        if (paasFormDataEntityExt == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_DATA_NOT_EXIST);
        }
        paasFormDataEntityExt.setBusinessType(businessType);
        paasFormDataEntityExt.setSaasMark(saasMark);
        return paasFormDataEntityExt;
    }
    /**
     * 获取带团队(负责人/协同人)的表单数据
     *
     * @param corpid
     * @param saasMark
     * @param businessType
     * @param dataId
     * @return
     * @throws XbbException
     */
    public PaasFormDataEntityExt getFormDataWithTeam(String corpid, Integer saasMark, Integer businessType, Long dataId) throws XbbException {
        PaasFormDataEntityExt paasFormDataEntityExt = getFormData(corpid, saasMark, businessType, dataId);
        Map<Long, List<String>> ownerIdMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Map<Long, List<String>> coUserIdMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        businessUserTeamHelp.getUserIdMapSetShow(new HashSet<>(), Collections.singletonList(dataId), corpid, businessType, false, ownerIdMap, coUserIdMap, DelEnum.NORMAL.getDel());
        paasFormDataEntityExt.getData().put(FieldTypeEnum.OWNERID.getAlias(), ownerIdMap.get(paasFormDataEntityExt.getId()));
        paasFormDataEntityExt.getData().put(FieldTypeEnum.COUSERID.getAlias(), coUserIdMap.get(paasFormDataEntityExt.getId()));
        return paasFormDataEntityExt;
    }


    /**
     * 获取实体，会返回异常的
     * @param corpid
     * @param saasMark
     * @param businessType
     * @param dataId
     * @return
     * @throws XbbException
     */
    public PaasFormDataEntityExt getFormDataEntityExt(String corpid, Integer saasMark, Integer businessType, Long dataId) throws XbbException {
        PaasFormDataEntityExt paasFormDataEntityExt = getFormData(corpid, saasMark, businessType, dataId);
        if (paasFormDataEntityExt == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_DATA_NOT_EXIST);
        }
        return paasFormDataEntityExt;
    }
    /**
     * Saas获取单条业务数据
     *
     * @param formDataId   表单数据id
     * @param corpid       公司id
     * @param businessType 业务类型
     * @return 封装了数据的业务数据实体
     * @author chaoxiong.lei
     * @date 14:00 2019/1/22
     * @since v1.0
     **/
    public PaasFormDataEntityExt getFormData(Long formDataId, String corpid, Integer businessType) {
        if (formDataId == null || corpid == null || businessType == null) {
            return null;
        }
        if (Objects.equals(businessType,XbbRefTypeEnum.CUSTOMER_STAGE.getCode())){
            businessType = XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode();
        }
        RedundantTemplateTypeEnum templateTypeEnum = RedundantTemplateTypeEnum.getByCode(businessType);
        PaasFormDataEntityExt paasFormDataEntityExt = new PaasFormDataEntityExt();
        switch (templateTypeEnum) {
            case CUSTOMER:
                paasFormDataEntityExt = customerModel.getByKey(formDataId, corpid);
                break;
            case CONTRACT:
            case ORDER:
                paasFormDataEntityExt = contractModel.getByKey(formDataId, corpid);
                break;
            case CONTACT:
                paasFormDataEntityExt = contactModel.getByKey(formDataId, corpid);
                break;
            case OUTSTOCK:
            case CONTRACT_OUTSTOCK:
            case PRODUCTION_MATERIEL_OUTSTOCK:
            case WORK_ORDER_OUTSTOCK:
            case OTHER_OUTSTOCK:
            case RETURNED_PURCHASE_OUTSTOCK:
                paasFormDataEntityExt = outstockModel.getByKey(formDataId, corpid);
                break;
            case SUPPLIER:
                paasFormDataEntityExt = supplierModel.getByKey(formDataId, corpid);
                break;
            case INVENTORY:
                paasFormDataEntityExt = inventoryModel.getByKey(formDataId, corpid);
                break;
            case TRANSFER:
                paasFormDataEntityExt = transferModel.getByKey(formDataId, corpid);
                break;
            case WAREHOUSE:
                paasFormDataEntityExt = warehouseModel.getByKey(formDataId, corpid);
                break;
            case SUPPLIER_CONTACT:
                paasFormDataEntityExt = supplierContactModel.getByKey(formDataId, corpid);
                break;
            case PURCHASE:
                paasFormDataEntityExt = purchaseModel.getByKey(formDataId, corpid);
                break;
            case RETURNED_PURCHASE:
                paasFormDataEntityExt = returnedPurchaseModel.getByKey(formDataId, corpid);
                break;
            case SALES_OPPORTUNITY:
                paasFormDataEntityExt = opportunityModel.getByKey(formDataId, corpid);
                break;
            case PAYMENT:
                paasFormDataEntityExt = paymentModel.getByKey(formDataId, corpid);
                break;
            case INVOICE:
                paasFormDataEntityExt = invoiceModel.getByKey(formDataId, corpid);
                break;
            case PURCHASE_INVOICE:
                paasFormDataEntityExt = purchaseInvoiceModel.getByKey(formDataId, corpid);
                break;
            case COMMUNICATE:
                paasFormDataEntityExt = customerCommunicateModel.getByKey(formDataId, corpid);
                break;
            case JXC_COMMUNICATE:
                paasFormDataEntityExt = supplierCommunicateModel.getByKey(formDataId, corpid);
                break;
            case COMMUNICATE_PLAN:
                paasFormDataEntityExt = communicatePlanModel.getByKey(formDataId, corpid);
                break;
            case BOMBILL:
                paasFormDataEntityExt = bomBillModel.getByKey(formDataId, corpid);
                break;
            case PRODUCTIONORDER:
                paasFormDataEntityExt = productionOrderModel.getByKey(formDataId, corpid);
                break;
            case ASSEMBLE:
                paasFormDataEntityExt = assembleModel.getByKey(formDataId, corpid);
                break;
            case INSTOCK:
            case PURCHASE_INSTOCK:
            case OTHER_INSTOCK:
            case REFUND_INSTOCK:
            case PRODUCTION_INSTOCK:
            case RETURNED_MATERIEL_INSTOCK:
                paasFormDataEntityExt = instockModel.getByKey(formDataId, corpid);
                break;
            case WORKREPORT_DAILY:
            case WORKREPORT_WEEKLY:
            case WORKREPORT_MONTHLY:
            case WORKREPORT:
                paasFormDataEntityExt = workReportModel.getByKey(formDataId, corpid);
                break;
            case PRODUCT:
                paasFormDataEntityExt = productModel.getByKey(formDataId, corpid);
                break;
            case PAY_PLAN:
                paasFormDataEntityExt = payPlanModel.getByKey(formDataId, corpid);
                break;
            case REFUND:
            case RETURN:
                paasFormDataEntityExt = refundModel.getByKey(formDataId, corpid);
                break;
            case PAYMENT_SHEET:
                paasFormDataEntityExt = paymentSheetModel.getByKey(formDataId, corpid);
                break;
            case PAY_SHEET:
                paasFormDataEntityExt = payPlanSheetModel.getByKey(formDataId, corpid);
                break;
            case WORKORDER:
                WorkOrderEntity workOrderEntity = workOrderModel.getByKey(formDataId, corpid);
                if (Objects.nonNull(workOrderEntity)) {
                    BeanUtil.copyProperties(workOrderEntity, paasFormDataEntityExt);
                    paasFormDataEntityExt.setBusinessType(XbbRefTypeEnum.WORK_ORDER.getCode());
                }
                break;
            case QUOTATION:
                paasFormDataEntityExt = quotationModel.getByKey(formDataId, corpid);
                break;
            case REIMBURSEMENT_FORM:
                paasFormDataEntityExt = reimbursementFormModel.getByKey(formDataId, corpid);
                break;
            case EXPENSE:
                paasFormDataEntityExt = expenseModel.getByKey(formDataId, corpid);
                break;
            case CLUE:
                paasFormDataEntityExt = clueModel.getByKey(formDataId, corpid);
                break;
            case MARKET_ACTIVITY:
                paasFormDataEntityExt = marketActivityModel.getByKey(formDataId, corpid);
                break;
            case PAYMENT_TASK:
                paasFormDataEntityExt = paymentTaskModel.getByKey(formDataId, corpid);
                break;
            case CREDIT_LIMIT:
                paasFormDataEntityExt = creditLimitModel.getByKey(formDataId, corpid);
                break;
            case CREDIT_FIXED_LIMIT:
                paasFormDataEntityExt = creditFixedLimitModel.getByKey(formDataId, corpid);
                break;
            case CREDIT_TEMPORARY_LIMIT:
                paasFormDataEntityExt = creditTemporaryLimitModel.getByKey(formDataId, corpid);
                break;
            case CREDIT_CARD_BILL:
                paasFormDataEntityExt = creditCardBillModel.getByKey(formDataId, corpid);
                break;
            case CUSTOMER_STATEMENT:
                paasFormDataEntityExt = customerStatementModel.getByKey(formDataId, corpid);
                break;
            case CUSTOMER_STATEMENT_STATISTIC:
                paasFormDataEntityExt = customerStatementStatisticsModel.getByKey(formDataId, corpid);
                break;
            case CUSTOMER_STATEMENT_SNAPSHOT:
                paasFormDataEntityExt = customerStatementSnapshotModel.getByKey(formDataId, corpid);
                break;
            case PROMOTION_ACTIVITY_MANAGEMENT:
                paasFormDataEntityExt = promotionActivityModel.getByKey(formDataId, corpid);
                break;
            case WRITE_OFF_RECORD:
                paasFormDataEntityExt = writeOffRecordModel.getByKey(formDataId, corpid);
                break;
            case DISTRIBUTOR_ACCOUNT:
                DistributorAccountEntity distributorAccountEntity = distributorAccountModel.getByKey(formDataId, corpid);
                CustomerEntityExt customerEntityExt = customerModel.getByKey(distributorAccountEntity.getDistributorId(), corpid);
                PaasFormDataEntity paasFormDataEntity = distributorAccountTransferSubForm.transferEntityToFormData(distributorAccountEntity);
                paasFormDataEntity.getData().put(DistributorAccountEnum.DISTRIBUTOR_NAME_LINK_TEXT.getAttr(), customerEntityExt.getData().getString(DistributorEnum.NAME.getAttr()));
                paasFormDataEntity.setAppId(customerEntityExt.getAppId());
                BeanUtil.copyProperties(paasFormDataEntity, paasFormDataEntityExt, true);
                break;
            case ONLINE_PAYMENT_FLOW:
                OnlinePaymentFlowEntity onlinePaymentFlowEntity = onlinePaymentFlowModel.getByKey(formDataId, corpid);
                BeanUtil.copyProperties(onlinePaymentFlowEntity, paasFormDataEntityExt);
                break;
            case FUND_TRANSFER:
                paasFormDataEntityExt = fundTransferModel.getByKey(formDataId, corpid);
                break;
            case OTHER_INCOME:
                paasFormDataEntityExt = otherIncomeModel.getByKey(formDataId, corpid);
                break;
            case OTHER_EXPENSE:
                paasFormDataEntityExt = otherExpenseModel.getByKey(formDataId, corpid);
                break;
            case SALE_STAGE:
                paasFormDataEntityExt  = opportunityModel.getByKey(formDataId, corpid);
                break;
            case CLUE_STAGE:
                paasFormDataEntityExt = clueModel.getByKey(formDataId, corpid);
                break;
            case COST_ADJUST:
                paasFormDataEntityExt = costAdjustModel.getByKey(formDataId, corpid);
                break;
            case COMPETITOR:
                paasFormDataEntityExt = competitorModel.getByKey(formDataId, corpid);
                break;
            case SERVICE_PROJECT:
            case WORK_ORDER_V2:
            case RECEIPT_ORDER:
            case SLA_LOG:
                try {
                    IndexTypeEnum indexTypeEnum = indexTypeModel.getIndexType(corpid, businessType, SaasMarkEnum.SAAS.getCode());
                    paasFormDataEntityExt = paasEsModel.getByKey(formDataId, corpid, indexTypeEnum, null);
                    if (Objects.nonNull(paasFormDataEntityExt)) {
                        IndexTypeEnum subIndex = indexTypeModel.getSubIndexType(corpid, businessType, SaasMarkEnum.SAAS.getCode());
                        List<PaasFormSubDataEntity> list = paasFormSubDataEsModel.getSubDataByParentId(corpid, SaasMarkEnum.SAAS.getCode(), businessType, null, paasFormDataEntityExt.getFormId(), Arrays.asList(paasFormDataEntityExt.getDataId()), 1, null, subIndex);
                        if (CollectionUtils.isNotEmpty(list)) {
                            FormSubDataUtil.setSubDataBySingle(paasFormDataEntityExt, list);
                        }
                    }
                } catch (XbbException e) {
                    LOG.warn("com.xbongbong.paas.help.FormDataHelp.getFormData", e);
                } catch (Exception e) {
                    LOG.error("com.xbongbong.paas.help.FormDataHelp.getFormData", e);
                }
                break;
            default:
                paasFormDataEntityExt = null;
                break;
        }
        return paasFormDataEntityExt;
    }

    /**
     * 只存数据库未存es数据处理
     * 重构前 -> com.xbongbong.saas.help.SaasListHelp#setOnlyDBData(com.xbongbong.paas.pojo.dto.FormDataListDTO, com.xbongbong.paas.pojo.vo.PaasFormDataEsListVO)
     * @throws XbbException
     */
    public void setOnlyDBData(Integer businessType, Integer distributorMark, String corpid, Integer subBusinessTYpe, List<PaasFormDataEntityExt> list) throws XbbException {
        // 枚举获取
        if (!OnlyInsertDBEnum.containBusinessType(businessType, distributorMark)) {
            return;
        }
        if (CollectionsUtil.isEmpty(list)) {
            return;
        }

        XbbRefTypeEnum xbbRefTypeEnum = XbbRefTypeEnum.getByCode(businessType);


        List<Long> dataIdList = new ArrayList<>();
        list.forEach(item -> dataIdList.add(item.getDataId()));

        // todo 字段解释是否有权限
        List<String> attrList = OnlyInsertDBEnum.getAttrByBusinessType(businessType, distributorMark);
        String dataSql = FormDataUtil.getDataColumns(attrList);
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put(StringConstant.CORPID, corpid);
        param.put(StringConstant.DEL, DelEnum.NORMAL.getDel());
        param.put(StringConstant.IDIN, dataIdList);
        // 查询部分数据
        param.put(StringConstant.COLUMNS, "id, " + dataSql);
        switch (xbbRefTypeEnum) {
            case CONTACT:
                List<ContactEntityExt> contactList = contactModel.findEntitys(param);
                Map<Long, JSONObject> contactMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                for (ContactEntityExt entityExt : contactList) {
                    contactMap.put(entityExt.getId(), entityExt.getData());
                }
                for (PaasFormDataEntityExt paasFormDataEntityExt : list) {
                    JSONObject data = contactMap.get(paasFormDataEntityExt.getDataId());
                    if (Objects.isNull(data)) {
                        continue;
                    }
                    OnlyInsertDBHelp.setData(businessType, distributorMark, data, paasFormDataEntityExt.getData());
                }
                break;
            default:
                break;
        }
    }
}
